package lb

import (
	"github.com/lafikl/consistent"
	log "github.com/sirupsen/logrus"
	"hash/crc32"
)

//hash
type HashBalancer struct {
}

func (r *HashBalancer) Next(key string, hosts []*HostInstance) *HostInstance {
	//hash
	count := crc32.ChecksumIEEE([]byte(key))
	//取模计算索引
	index := int(count) % len(hosts)
	//按索引取出实例
	instance := hosts[index]
	return instance
}

//lafikl/consistent一致性hash
type ConsistentHashBalancer struct {
}

func (r *ConsistentHashBalancer) Next(key string, hosts []*HostInstance) *HostInstance {
	c := consistent.New()
	for _, ins := range hosts {
		c.Add(ins.InstanceId)
	}
	instanceId, err := c.Get(key)
	if err != nil {
		log.Fatal(err)
	}
	for _, ins := range hosts {
		if instanceId == ins.InstanceId {
			return ins
		}
	}

	return nil
}

//一致性hash
type ConsistentHash struct {
	logicNodeSize int   //逻辑节点数
	ringNodes     []int //环形节点，
}

func (c *ConsistentHash) Get() {

}
